package main

import (
	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
	"golang.org/x/time/rate"
	"net/http"
	"time"
)

func main() {
	e := echo.New()
	e.Use(middleware.Logger())
	//自定义
	e.Use(middleware.RateLimiterWithConfig(CustomRateLimiterConfig()))
	e.GET("/index", Index)
	e.Start(":80")
}
func Index(c echo.Context) error {
	return c.String(200, "hello world")
}

func CustomRateLimiterConfig() middleware.RateLimiterConfig {
	config := middleware.RateLimiterConfig{
		Skipper: middleware.DefaultSkipper,
		Store: middleware.NewRateLimiterMemoryStoreWithConfig(
			middleware.RateLimiterMemoryStoreConfig{Rate: rate.Limit(2), Burst: 30, ExpiresIn: 3 * time.Second},
		),
		IdentifierExtractor: func(ctx echo.Context) (string, error) {
			id := ctx.RealIP()
			return id, nil
		},
		ErrorHandler: func(context echo.Context, err error) error {
			return context.JSON(http.StatusForbidden, "StatusForbidden")
		},
		DenyHandler: func(context echo.Context, identifier string, err error) error {
			return context.JSON(http.StatusTooManyRequests, "StatusTooManyRequests")
		},
	}
	return config
}
